﻿
// var requestloginUrl = "http://localhost:8080" + "/Triage/login";
var requestloginUrl = STSUrl + "/Triage/login";
var requestloginUrlVerify = STSUrl + "/Triage/loginVerify";
// var requestloginUrlVerify = "http://localhost:8080" + "/Triage/loginVerify";
var remindUrl = SystemLimitUrl + "/user/loginAlert";//到期提醒AjaxUrl
var noremindUrl = SystemLimitUrl + "/user/doNotAlert";//一段时间内不再提醒授权到期时间AjaxUrl

$(function () {
    //从c端获取医生账号 
    //try { my_cefsharp.Get_UserName_Cef(getDoctorLoginID); } catch (err) { }

    $("#loginBut").prop("", "");
    $("#txt_userid").on("input ", function () {
        //验证用户名
        userLongin();
    });

    $("#txt_userid").on('input propertychange', function () {
        closeUserHistroy();
    });

    $("#txt_userpwd").on("input ", function () {
        pwdValidate();
    });
});



//验证密码
function pwdValidate() {

    //验证密码
    var pwd_len = $("#txt_userpwd").val().length;
    if (pwd_len > 0) {
        $("#img-for-txt_userpwd").css("border", '');
        $("#msg-for-txt_userpwd").html("&nbsp;");
        $("#txt_userpwd").css("border", '');
        $("#img-for-txt_userpwd").css("background-color", "#19C5A5");
    } else {
        $("#img-for-txt_userpwd").css("background-color", "#EEEEEE");
        $("#msg-for-txt_userpwd").html("密码长度至少1位");
        $("#msg-for-txt_userpwd").css({ "color": "red", "font-weight": "bold" });
    }
}


//验证用户名
function userLongin() {
    var user_len = $("#txt_userid").val().trim().length;
    if (user_len >= 1 && user_len < 21) {
        $("#img-for-txt_userid").css("border", '');
        $("#msg-for-txt_userid").html("&nbsp;");
        $("#txt_userid").css("border", '');
        $("#img-for-txt_userid").css("background-color", "#19C5A5");
    } else {
        $("#img-for-txt_userid").css("background-color", "#EEEEEE");
        $("#msg-for-txt_userid").html("登录ID限制在1-20位");
        $("#msg-for-txt_userid").css({ "color": "red", "font-weight": "bold" });
    }
}


//存储当前医生的登录账户传给c端
function setDoctorLoginID(data) {
    try { my_cefsharp.Set_UserName_Cef(data); } catch (err) { }
}

//从c端获取上次登陆的账号名进行返显
function getDoctorLoginID(s) {

    //s = "sss,111,444,dasd,"
    console.log(s);
    if (s == undefined)
        return;
    var userArr = s.split(",");
    var userList = "<ul class='user-histroy'>";
    for (var i = 0; i < userArr.length  ; i++) {
        if (userArr[i] == undefined || userArr[i] == "")
            continue;
        var _userId = userArr[i];
        userList += "<li>" + _userId + "</li>";
    }

    userList += "</ul>";
    $("#txt_userid").prev("span").append(userList);
    $(".user-histroy>li").on("click", function () {
        console.log($(this).prop("id") + "__" + $(this).html());
        $("#txt_userid").val($(this).html());
        $("#txt_userid").prev("span").find("ul").remove();
        userLongin();
    });
}




//[废弃]
function closeUserHistroy() {
    $("#txt_userid").prev("span").find("ul").remove();
}

//注册输入框获取焦点事件[废弃]
function loginUserHistroy() {

    $("#txt_userid").prev("span").find("ul").remove();
    try { my_cefsharp.Get_UserName_Cef(getDoctorLoginID); } catch (err) { };

    //var _localUserStore = window.localStorage;
    //var loginUserJson = _localUserStore["__LOGINUSER__"];
    //if (loginUserJson != undefined) {

    //    var count = 0;
    //    var userList = "<ul class='user-histroy'>";
    //    for (var i = JSON.parse(loginUserJson).length - 1; i >= 0 ; i--) {
    //        if (count > 4)
    //            break;
    //        var _userId = JSON.parse(loginUserJson)[i]._uId;
    //        var _userPwd = JSON.parse(loginUserJson)[i]._Pwd;
    //        console.log(_userId + "__" + _userPwd);
    //        userList += "<li id='" + _userPwd + "'>" + _userId + "</li>";
    //        count++;
    //    }

    //    userList += "</ul>";
    //    $("#txt_userid").prev("span").append(userList);
    //    $(".user-histroy>li").on("click", function () {
    //        console.log($(this).prop("id") + "__" + $(this).html());
    //        $("#txt_userid").val($(this).html());
    //        $("#txt_userpwd").val($(this).prop("id"));
    //        $("#txt_userid").prev("span").find("ul").remove();
    //        userLongin();
    //    });
    //}
};

//更新已经登陆医生存储信息[废弃]
var updateLoginUser = function (uId, uPwd) {

    var _localUserStore = window.localStorage;

    //首次登陆，构建一个存储
    if (_localUserStore["__LOGINUSER__"] == undefined) {

        var userInfoArr = [];
        var userInfo = new Object;
        userInfo._uId = uId;
        userInfo._Pwd = uPwd;
        userInfoArr.push(userInfo);
        _localUserStore["__LOGINUSER__"] = JSON.stringify(userInfoArr);

    } else {

        var _userJsonInfo = JSON.parse(_localUserStore["__LOGINUSER__"]);

        //更新
        var isUpdate = false;
        for (var i = 0; i < _userJsonInfo.length; i++) {
            console.log(_userJsonInfo[i]._uId);
            if (_userJsonInfo[i]._uId == uId) {
                _userJsonInfo[i]._uId = uId;
                _userJsonInfo[i]._Pwd = uPwd;
                isUpdate = true;
                break;
            }
        }
        _localUserStore["__LOGINUSER__"] = JSON.stringify(_userJsonInfo);

        //新增
        if (!isUpdate) {
            var userInfo = new Object;
            userInfo._uId = uId;
            userInfo._Pwd = uPwd;
            _userJsonInfo.push(userInfo);
            //更新存储
            _localUserStore["__LOGINUSER__"] = JSON.stringify(_userJsonInfo);
        }
    }
    console.log(JSON.parse(_localUserStore["__LOGINUSER__"]));
};


$(document).keypress(function (e) {
    if (e.which == 13) {
        toValidate();
    }
});

function toValidate() {

    var _uId = $("#txt_userid").val();
    var _pwd = $("#txt_userpwd").val();

    if (pattern.test(_uId)) {
        layer.alert("用户名不能包含特殊字符.", { icon: 2 });
        return false;
    }
    if (pattern.test(_pwd)) {
        layer.alert("密码不能包含特殊字符.", { icon: 2 });
        return false;
    }

    var val = new validate({
        rules: {
            txt_userid: "userIdEmpty",
            txt_userpwd: "passwordEmpty"
        },
        /*submitFun里面为检验成功后要执行的方法*/
        submitFun: function () {
            if (_uId.length < 1)
                return;
            if (_pwd.length == 0)
                return;

            var _deviceType = getLocalDeviceCookie("LOCAL_DEV_TYPE") == null ? "1" : getLocalDeviceCookie("LOCAL_DEV_TYPE");
            var _hospitalId = getLocalDeviceCookie("HOSPITAL_ID") == null ? "4e66fabafd944e458dc259ce890c31f3" : getLocalDeviceCookie("HOSPITAL_ID");
            var _deviceId = getLocalDeviceCookie("C_OR_T_ID") == null ? "" : getLocalDeviceCookie("C_OR_T_ID");
            var _loginToken = getLocalDeviceCookie("LOGIN_TOKEN") == null ? "" : getLocalDeviceCookie("LOGIN_TOKEN");
            var _loginUseName = $("#txt_userid").val();
            var _loginPwd = $("#txt_userpwd").val();

            $.ajax({
                url: requestloginUrlVerify,
                type: 'get',
                data: {
                    deviceType: _deviceType,
                    deviceId: _deviceId,
                    hospitalId: _hospitalId,
                    loginName: _loginUseName,
                    loginPwd: _loginPwd,
                    loginToken: _loginToken
                },
                success: function (d) {
                    //存储选择记录的账号
                    //if($("#selectiveMemory").prop("checked")==true){
                    setDoctorLoginID(_uId);
                    //}

                    //登陆成功后，保存五个登陆成功的ID。[废弃]
                    //updateLoginUser(_uId, _pwd);


                    var resObj = JSON.parse(d);
                    if (resObj.status == '0') {
                        var dataObj = resObj.data;
                        var _userId = dataObj.userId;
                        var _name = dataObj.name;
                        var _deptName = dataObj.deptName;
                        var _usedDeviceId = dataObj.usedDeviceId;
                        var _ip = dataObj.ip;
                        var _positionStr = dataObj.positionStr;
                        var _triageName = dataObj.triageName;
                        var _deptId = dataObj.deptId;
                        var _padStatus = dataObj.pwdStatus;

                        requestAction(_name, _deptName, _usedDeviceId, _ip, _positionStr, _triageName, _deptId, _deviceId, _userId, _hospitalId, _loginUseName, _padStatus, _ip);
                    } else if (resObj.status == '19991') {
                        var dataObj = resObj.data;
                        var _userId = dataObj.userId;
                        var _name = dataObj.name;
                        var _deptName = dataObj.deptName;
                        var _usedDeviceId = dataObj.usedDeviceId;
                        var _ip = dataObj.ip;
                        var _positionStr = dataObj.positionStr;
                        var _triageName = dataObj.triageName;
                        var _deptId = dataObj.deptId;
                        var _padStatus = dataObj.pwdStatus;

                        /*layui弹窗，新加*/
                        layer.open({
                            content: resObj.desc,
                            btn: ['确定', '取消'],
                            yes: function (index, layero) {
                                layer.close(index);
                                requestAction(_name, _deptName, _usedDeviceId, _ip, _positionStr, _triageName, _deptId, _deviceId, _userId, _hospitalId, _loginUseName, _padStatus, _ip);
                            }
                        });
                    } else if (resObj.status == '19994') {
                        layer.open({
                            content: "抱歉，当前终端已经被删除，请重新注册或联系系统管理员！",
                            btn: ['确定', '取消'],
                            yes: function (index, layero) {
                                layer.close(index);
                                my_cefsharp.CefSharp_Reset_Server();
                            }
                        });
                    } else {
                        layer.alert(resObj.desc, { icon: 2 });
                    }
                }, error: function (XMLHttpRequest, textStatus, errorThrown) {
                    layer.alert("请求失败-" + XMLHttpRequest.status + " textStatus-" + XMLHttpRequest.readyState + " errorThrown-" + textStatus);
                }
            });
        }
    });
}

//登录
function requestAction(name, deptName, usedDeviceId, ip, positionStr, triageName, deptId, deviceId, userId, hospitalId, userName, pwdStatus) {
    var _ip = getLocalDeviceCookie("LOCAL_DEV_IP") == null ? "" : getLocalDeviceCookie("LOCAL_DEV_IP");
    $.ajax({
        url: requestloginUrl,
        type: 'post',
        data: {
            name: name,
            deptName: deptName,
            usedDeviceId: usedDeviceId,
            ip: ip,
            positionStr: positionStr,
            triageName: triageName,
            deptId: deptId,
            deviceId: deviceId,
            userId: userId,
            hospitalId: hospitalId,
            newIp: _ip
        },
        success: function (d) {
            var resObj = JSON.parse(d);
            if (resObj.status == '0') {
                var dataObj = resObj.data;
                var _userId = dataObj.userId;
                var _name = dataObj.name;
                var _deptName = dataObj.deptName;
                var _nextPageKey = dataObj.nextPageKey;
                var _deptId = dataObj.deptId;

                setCookie("deviceId", deviceId);
                setCookie("userId", _userId);
                setCookie("name", _name);
                setCookie("deptName", _deptName);
                setCookie("deptId", _deptId);
                setCookie("pwdStatus", pwdStatus);

                LoginSuccess(userName);

                //闽东版本-去掉此逻辑
                //如果用户首次登录，应该强制更改密码 1：初始密码（默认密码123456）
                //                                   2：密码重置（默认密码123456）
                //                                   3：用户密码（用户修改后的密码）
                //if (pwdStatus == 1 || pwdStatus == 2) {
                //    layer.alert("系统检测到您是首次登录，为了您的账号安全，请先前往设置修改密码.", {
                //        closeBtn: 0,
                //        btn: ['确定'],
                //        icon: 7,
                //        yes: function (index) {
                //            RedirectByKey("Setting.nurse");
                //        }
                //    });
                //} else if (pwdStatus == 2) {
                //    layer.alert("系统检测到您对密码进行了重置，为了您的账号安全，请先前往设置修改密码.", {
                //        closeBtn: 0,
                //        btn: ['确定'],
                //        icon: 7,
                //        yes: function (index) {
                //            RedirectByKey("Setting.nurse");
                //        }
                //    });
                //} else {
                    dueReminder(90,hospitalId,_userId,_nextPageKey);
                    //RedirectByKey(_nextPageKey);
                //}
            } else if (resObj.status == '19994') {
                layer.alert("抱歉，当前终端已经被删除，请重新注册或联系系统管理员！", { icon: 2 });
                my_cefsharp.CefSharp_Reset_Server();
            } else {
                layer.alert(resObj.desc, { icon: 2 });
            }
        }, error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("请求失败-" + XMLHttpRequest.status + " textStatus-" + XMLHttpRequest.readyState + " errorThrown-" + textStatus);
        }
    });

}
/**
 *  到期提醒
 *  @parsm day Number 授权到期提前提醒天数
 * */
function dueReminder(day,hid,uid,_nextPageKey){
    day = day ||  90;
    $.ajax({
        url: remindUrl,
        type: 'post',
        async:false,
        data: {
            day: day,
            hospitalId:hid,
            userId:uid
        },
        success: function (d) {
            if(d!=''){
                d = JSON.parse(d);
                var frag = '<div style="padding: 30px">系统到期时间为<span style="color: red">'+d.data+'</span>，请尽早处理,防止影响使用！</div>';
                if (d.status == 10001) {
                    layer.open({
                        type: 1,
                        title:'提醒',
                        anim: 2,
                        area: ['400px','240px'],
                        closeBtn:false,
                        maxHeight:'200px',
                        shadeClose: true, //开启遮罩关闭
                        content:frag,
                        btn: ['30天内不再提醒','确认'],
                        btn1: function(index, layero){
                            // 一个月内不再提醒
                            layer.close(index);
                            doNotAlert(30,hid,uid);
                            RedirectByKey(_nextPageKey);
                        },
                        btn2:function (index,layero){
                            //确认
                            RedirectByKey(_nextPageKey);
                        }
                    });

                }else {
                    RedirectByKey(_nextPageKey);
                }
            }else {
                RedirectByKey(_nextPageKey);
            }
        }
    });
}
/**
 *  一段时间内不再提醒到期提醒
 *  @parsm day Number 多少天内不再提醒
 * */

function doNotAlert(day,hid,uid){
    day = day ||  30;
    $.ajax({
        url: noremindUrl,
        type: 'post',
        async:false,
        data: {
            day: day,
            hospitalId:hid,
            userId:uid
        },
        success: function (d) {
            if(d!=''){
                d = JSON.parse(d);
                if (d.status != 0) {
                    layer.msg(d.desc||'发生错误，请联系管理员！');
                }
            }
        }
    });
}

